package vim.meet.javassist.base;

import javassist.*;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;

import java.io.IOException;
import java.lang.reflect.Modifier;

public class ClassPoolTest {
	
	public static void main(String[] args) {
		ClassPool cp = ClassPool.getDefault();
		try {
//			CtClass cc = cp.get("Point");//必须全限定名
			CtClass cc = cp.get("cn.freemethod.bean.Point");
			byte[] bs = cc.toBytecode();
			System.out.println(bs.length);
//			cc.writeFile();
		} catch (NotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (CannotCompileException e) {
			e.printStackTrace();
		}
		dealParaName();
	}
	
	/**
	 * javac -g Hello.java 生成所有调试信息
	 */
	 public static void dealParaName(){
         
         ClassPool pool = ClassPool.getDefault();  
         CtClass cc = null;
         try {
             cc = pool.get("cn.freemethod.bean.Point");
         } catch (NotFoundException e) {
             e.printStackTrace();
         }  
         CtMethod [] cms = cc.getDeclaredMethods();
   
         for(CtMethod cm : cms){
             if(!Modifier.isPublic(cm.getModifiers()))
                 continue;
             cc.defrost();//当CtClass 调用writeFile()、toClass()、toBytecode() 这些方法的时候，Javassist会冻结CtClass Object
             MethodInfo methodInfo = cm.getMethodInfo();  
             CodeAttribute codeAttribute = methodInfo.getCodeAttribute();  
             LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);  
             if (attr == null) {  
                 // exception
                 return;
             }  
             String[] paramNames = null;
             try {
                 paramNames = new String[cm.getParameterTypes().length];
             } catch (NotFoundException e) {
                 e.printStackTrace();
             }  
             int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;  
             for (int i = 0; i < paramNames.length; i++)  
                 paramNames[i] = attr.variableName(i + pos);  
             // paramNames即参数名  
             for (int i = 0; i < paramNames.length; i++) {  
                 System.out.println(paramNames[i]);  
             }  
     }
 }

}
